package com.sto.stoapp.activity.scanner;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.dataprocess.ProcessScanCode;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.status.EnumScanCode;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoListenerActivity;

import java.util.ArrayList;
import java.util.List;

@SuppressLint("HandlerLeak")
public class StoScanReachCarScanActivity extends StoListenerActivity {

	// private StoHhmEditText code;
	private DataBusinessEntity dataBusiness;

	private List<EditText> edit = new ArrayList<EditText>();

	private String busiType = HomeBroadAction.SCANNER_MAN_BROAD;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sto_reach_car_scan);
		Bundle extras = getIntent().getExtras();
		busiType = extras.getString("busiType");
		this.setTitleBottom(R.string.to_car_piece_scan, busiType);
		initPointLayout(true);
		initWidget();
		initListen();
		initScanListener();
		dataBusiness = new DataBusinessEntity();
		dataBusiness.initInsertData();
		if (busiType.equals(HomeBroadAction.SCANNER_MAN_BROAD)) {
			initScanRecordAdapter(EnumTableNames.STATUS_TABLE_RECEIVE_CAR);
		} else if (busiType.equals(HomeBroadAction.CENTER_BROAD)) {
			initScanRecordAdapter(EnumTableNames.STATUS_TABLE_CENTER_RECEIVE_CAR);
		}
		/*
		 * 航空-扫描员-到件
		 * 
		 * @修改人：mgf
		 */
		else if (busiType.equals(HomeBroadAction.AVIATION_SCANNER_BROAD)) {
			initScanRecordAdapter(EnumTableNames.STATUS_TABLE_AVIATION_RECEIVE_CAR);
		}
	}

	private void initWidget() {

		code = (StoHhmEditText) this.findViewById(R.id.sanning_code);
		// code.setInputType(InputType.TYPE_CLASS_TEXT);
		//code.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
		// ticketNumber = (TextView)
		// this.findViewById(R.id.nophone_tickets_text);
		// edit.add(code);
		if (busiType.equals(HomeBroadAction.SCANNER_MAN_BROAD)) {

			addUploadTable(EnumTableNames.STATUS_TABLE_RECEIVE_CAR);
		} else if (busiType.equals(HomeBroadAction.CENTER_BROAD)) {

			addUploadTable(EnumTableNames.STATUS_TABLE_CENTER_RECEIVE_CAR);
		}
		// 航空-扫描员-到车
		else if (busiType.equals(HomeBroadAction.AVIATION_SCANNER_BROAD)) {

			addUploadTable(EnumTableNames.STATUS_TABLE_AVIATION_RECEIVE_CAR);
		} else {

		}
	}

	/**
	 * 扫描数据处理
	 */
	@SuppressLint("NewApi")
	private void processScanData() {
		try {
			if (!code.getText().toString().isEmpty()) {
				if (addPieceRecord()) {
					this.addCodeNumber();
					setSaveData(true);
					// SoundManager.getInstance(this).playSuccessSound();
					Helper.showSoundAndVibrator(this, true);
					addScanRecordInfo(code.getText().toString());
					// ticketNumber.setText(String.valueOf(++count));
					code.setSelection(code.length());

				}
				// 提示插入数据失败
				else {
					Helper.showSoundToast(this,
							getString(R.string.code_repeat), false);
				}
				ScanOpen();
			} else if (code.getText().toString().isEmpty()) {
				// 提示单号不能为空

			}

		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("processScanData", e.getMessage());
		}
	}

	/**
	 * 数据保存
	 * 
	 * @return true/成功 or false/失败
	 */
	private boolean addPieceRecord() {
		boolean ret = false;
		
		// 单号
		dataBusiness.setBar_code_number(code.getText().toString());

		dataBusiness.setCodeType(getExpType(code.getText().toString()));
		// 网点编号
		dataBusiness.setNet_code(StoFilePreference.getInstance(this)
				.getSiteCode());
		// 工号
		dataBusiness.setJob_number(StoFilePreference.getInstance(this)
				.getUserCode());
		if (busiType.equals(HomeBroadAction.SCANNER_MAN_BROAD)) {
			// 扫描类型
			dataBusiness.setCommand_type(EnumTableNames.STATUS_TABLE_RECEIVE_CAR.getOpCode());
			// 插入数据
			ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
					EnumTableNames.STATUS_TABLE_RECEIVE_CAR);
		} else if (busiType.equals(HomeBroadAction.CENTER_BROAD)) {
			// 扫描类型
			dataBusiness.setCommand_type(EnumTableNames.STATUS_TABLE_CENTER_RECEIVE_CAR.getOpCode());
			// 插入数据
			ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
					EnumTableNames.STATUS_TABLE_CENTER_RECEIVE_CAR);
		}
		// 航空-扫描员-到车
		else if (busiType.equals(HomeBroadAction.AVIATION_SCANNER_BROAD)) {
			// 扫描类型
			dataBusiness.setCommand_type(EnumTableNames.STATUS_TABLE_AVIATION_RECEIVE_CAR.getOpCode());
			ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
					EnumTableNames.STATUS_TABLE_AVIATION_RECEIVE_CAR);
		} else {

		}

		return ret;
	}

	/**
	 * 监听控件
	 */
	private void initListen() {

		code.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				onBackPressed();
			}

			@Override
			public void onEditClickListener(View v) {
				if (code.getText().toString().length() == 0) {
					Helper.showSoundToast(StoScanReachCarScanActivity.this,
							getString(R.string.code_empty), false);
				} else {
					onScanResults(code.getText().toString());
				}
			}
		});
		/*
		 * code.setOnClickListener(new StoOnClickListener(this) {
		 * 
		 * @Override public void mHonClick(View v) {
		 * onScanResults(code.getText().toString()); } });
		 */

		/*
		 * code.setEditScanListener(new EditScanListener() {
		 * 
		 * @Override public void onScan() { ScanOpen(); }
		 * 
		 * @Override public void offScan() { ScanOff(); } });
		 */

		code.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				if (code.getText().toString().trim().length() == 9
						&& Helper.isNumeric(code.getText().toString().trim())) {
					code.setText("STO" + code.getText().toString().trim());
					code.setSelection(12);
					// code.selectAll();
				} else if (code.getText().toString().trim().length() == 12) {

				} else if (code.getText().toString().trim().length() == 0) {

				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		/*
		 * for (EditText editListener : edit) {
		 * 
		 * 
		 * 监听EditText内容个数
		 * 
		 * editListener.addTextChangedListener(new TextWatcher() {
		 * 
		 * @Override public void onTextChanged(CharSequence s, int start, int
		 * before, int count) {
		 * 
		 * }
		 * 
		 * @Override public void beforeTextChanged(CharSequence s, int start,
		 * int count, int after) { }
		 * 
		 * @Override public void afterTextChanged(Editable s) {
		 * 
		 * } }); }
		 */
	}

	/**
	 * 扫描码判断
	 * 
	 * @param code
	 *            扫描码
	 * @return true/ok or false
	 */
	private boolean CheckScanCode(String code) {
		boolean ret = false;
		EnumScanCode status = ProcessScanCode.getInstance(this).ScanCodeResolve(
				code, EnumTableNames.STATUS_TABLE_RECEIVE_CAR);

		switch (status) {
		// 条码空
		case CODE_EMPTY:
			// Helper.showSoundToast(
			// this,
			// getString(R.string.code_empty), false);
			break;

		// 非法条码
		case CODE_ILLEGAL:
			Helper.showSoundToast(this, getString(R.string.error_code), false);
			break;
		// 非法条码
		case CAR_SEAL_ILLEGAL:
			Helper.showSoundToast(this, "非法铅封条码", false);
			break;
		// 成功条码
		case CODE_SEAL_OK:

			ret = true;
			break;
		default:
			break;
		}

		return ret;
	}

	@Override
	public void onBackPressed() {
		// 确定退出吗?
		showNotice();
		// super.onBackPressed();

	}

	@Override
	protected void handlerScanData(String scanData) {

		if (scanData != null && !scanData.equals("")) {
			String result = scanData.toString();
			code.setText(result);
			code.setSelection(code.length());

			if (CheckScanCode(result)) {
				processScanData();
			}
			code.setText("");
			code.requestFocus();
		} else {

		}

	}
}
